package com.alexatguigu.listener;


import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class OrderListener {
    @RabbitListener(queues = "order.queue")
    public void handleOrder(Message message, Channel channel) throws Exception {
        try {
            String msg = new String(message.getBody());
            // 模拟处理订单
            Thread.sleep(200);
            // 手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 判断是否重试过
            if (message.getMessageProperties().getRedelivered()) {
                // 消息已重试过,拒绝并丢弃
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                // 重新入队
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }
}
